import Taro from '@tarojs/taro';
import {getToken} from "@/utils/auth";

export interface HttpResponse<T = any> {
  msg: string;
  code: number;
  data: T;
}

export interface HttpError {
  msg: string;
  code: number;
}
//网络请求拦截器
const interceptor = function (chain) {
  const requestParams = chain.requestParams
  let token = getToken()
  // let token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE3NzEyMjAxNTQsInN1YiI6IjEifQ.smNKdUkZkpyH5YVc-BbrMNKZsYilQJVN2tOWW3dKH2s';
  requestParams.header = {
    ...requestParams.header,
    Authorization: 'Bearer ' + token //将token添加到头部
  }
  return chain.proceed(requestParams).then(res => { return res })
}

Taro.addInterceptor(interceptor)

const request = async (method, url, params) => {
  let contentType = params ? 'application/json' : 'application/x-www-form-urlencoded';
  if (params) contentType = params?.headers?.contentType || contentType;
  const option = {
    method,
    isShowLoading: false,
    url: process.env.TARO_APP_BASE_URL + url,
    data: params,
    header: {
      'content-type': contentType,
    },
    success(res) {
      console.log(res)
    },
    error(e) {
      console.log('api', '请求接口出现问题', e);
    }
  }
  const response = await Taro.request(option);
  const { code, data }: HttpResponse = response.data;
  if (code === 401) {
    // TODO: 处理 token 过期，自动刷新 token 或跳转登录界面
  }
  console.log(data)
  return data;
}

export default {
  get: (url, config={}) => {
    return request('GET', url, config);
  },
  post: (url, config) => {
    return request('POST', url, config);
  },
  put: (url, config={}) => {
    return request('PUT', url, config);
  },
  delete: (url, config={}) => {
    return request('DELETE', url, config);
  },
  patch: (url, config={}) => {
    return request('PATCH', url, config);
  },
}
